$(document).ready(function(){
    $('.m-navbar-header li').on('click',function(){
        $(this).addClass("active");
        $(this).siblings().removeClass("active");
        var navbar_li = $(this).attr("data");
        var num = $("#navbar_num").val();
        if(num != navbar_li){
            var num = $("#navbar_num").val(navbar_li);
            $('.data-one').hide();
            $('.data-two').hide();
            $('.data-three').hide();
            $('.data-four').hide();
            $('.data-five').hide();
            $('.data-six').hide();
            $('.data-seven').hide();
            if(navbar_li == 1){
                $('.data-one').show();
            }else if(navbar_li == 2){
                if($("#cangetmini").val() == 0){
                    $("#cangetmini").val(1);
                    miniReload();
                }
                $('.data-two').show();
            }else if(navbar_li == 3){
                if($("#cangetorder").val() == 0){
                    $("#cangetorder").val(1);
                    orderReload();
                }
                $('.data-three').show();
            }else if(navbar_li == 4){
                if($("#cangetwithdrawal").val() == 0){
                    $("#cangetwithdrawal").val(1);
                    withdrawalReload();
                }
                $('.data-four').show();
            }else if(navbar_li == 5){
                if($("#cangetnotes").val() == 0){
                    $("#cangetnotes").val(1);
                    notesReload();
                }
                $('.data-five').show();
            }else if(navbar_li == 6){
                $('.data-six').show();
            }else if(navbar_li == 7){
                if($("#cangetinvite").val() == 0){
                    $("#cangetinvite").val(1);
                    inviteReload();
                }
                $('.data-seven').show();
            }
        }
    })
});

function linksReload(){
    $("#links-lists").bootstrapTable('refresh');
}
function miniReload(){
    $("#mini-lists").bootstrapTable('refresh');
}

function orderReload(){
    $("#order-lists").bootstrapTable('refresh');
}

function withdrawalReload(){
    $("#withdrawal-lists").bootstrapTable('refresh');
}

function notesReload(){
    $("#notes-lists").bootstrapTable('refresh');
}

function inviteReload(){
    $("#invite-lists").bootstrapTable('refresh');
}


function linksLists(params){
    params.data.title = $("#link_title").val();
    params.data.nav = $("#navbar_num").val();
    params.data.page = Number(params.data.offset/params.data.limit) + 1;
    let users_id = $('#users_id').val();
    let url = users_id==0 ? `/admin/users/api_users_detial` : `/admin/users/api_users_detial/${users_id}`;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: params.data,
        success:function (result) {
            if (result.status == "success") {
                var linkLists = [];
                var platfrom_type_lists = ['','公众号文章','客服','客服','企业小程序','企业小程序','三方/个人小程序','复制添加微信','个人微信','微信群','朋友圈','小程序码','公众号二维码','H5网址','视频号主页','视频号直播','视频号视频'];
                $.each(result.data.data.data,function(key,item){
                    var name = item.status == 1 && item.name ? item.name : '-'
                    var disable = item.disable == 1 ? '<font class="text-success">可用</font>' : '<font class="text-danger">已删除</font>';
                    var limit_status = item.limit_status == 1 ? item.limit_pv : '不限制';
                    var method = '<a href="/admin/links_lists/links_lists_detial/'+item.links_id+'" class="text-primary">外链详情</a>';
                    var linkList = {"title":item.title,"name":name,"platfrom_type":platfrom_type_lists[item.platfrom_type],"disable":disable,"limit_status":limit_status,"left_pv":item.left_pv,"method":method};

                    linkLists.push(linkList);
                });
                var dataResult = {rows:linkLists,total:result.data.data.total};
                params.success(dataResult);
            } else {
                messageToastr("error",result.msg);
            }
        },
        error: function(err){
            messageToastr("error",'请求失败，请检查网络');
        }
    });
}

function miniLists(params){
    if($('#cangetmini').val() ==0) return false;
    params.data.name = $("#mini_name").val();
    params.data.nav = $("#navbar_num").val();
    params.data.page = Number(params.data.offset/params.data.limit) + 1;
    let users_id = $('#users_id').val();
    let url = users_id==0 ? `/admin/users/api_users_detial` : `/admin/users/api_users_detial/${users_id}`;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: params.data,
        success:function (result) {
            if (result.status == "success") {
                var linkLists = [];
                $.each(result.data.data.data,function(key,item){
                    var disablelist = ['','可用','<font class="text-danger">禁用</font>','<font class="text-success">使用中</font>'];

                    var distext = item.disable == 2 ? `<a class="text-primary" href="/admin/miniapp/minapp_disable/${item.appid}">解除</a>` : `<a class="text-danger" href="/admin/miniapp/minapp_disable/${item.appid}">禁用</a>`;

                    var method = `<a href="/admin/miniapp/minapp_update/${item.appid}" class="text-primary">更新</a> | <a class="text-success" href="/admin/miniapp/minapp_default/${item.appid}">设为默认</a> | ${distext} | <a href="javascript:;" class="text-danger" onclick='mviewNotification("error","删除提醒","删除小程序后链接可能无法使用,您确定要删除吗？","确认删除","取消",{"type":"mini_delete","appid":"${item.appid}"});'>删除</a>`;

                    var linkList = {"name":item.name,"disable":disablelist[item.disable],"appid":item.appid,"created_at":item.created_at,"method":method};
                    if(users_id != 0){
                        var status = item.ststus == 1 ? '私有' : '<font class="text-primary">公用</font>';
                        var types = ["","通用","公众号专用","二维码专用","客服专用","点击版专用","免费用户使用"];
                        linkList.status = status;
                        linkList.type = types[item.type];
                    }
                    linkLists.push(linkList);
                });
                var dataResult = {rows:linkLists,total:result.data.data.total};
                params.success(dataResult);
            } else {
                messageToastr("error",result.msg);
            }
        },
        error: function(err){
            messageToastr("error",'请求失败，请检查网络');
        }
    });
}

function orderLists(params){
    if($("#cangetorder").val() == 0) return false;
    params.data.invoice = $("#is_invoice").val();
    params.data.nav = $("#navbar_num").val();
    params.data.page = Number(params.data.offset/params.data.limit) + 1;
    let users_id = $('#users_id').val();
    let url = users_id==0 ? `/admin/users/api_users_detial` : `/admin/users/api_users_detial/${users_id}`;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: params.data,
        success:function (result) {
            if (result.status == "success") {
                var linkLists = [];
                var pay_status = ['','<font class="text-info">未支付</font>','<font class="text-info">待支付</font>','<font class="text-success">已支付</font>','<font class="text-success">已续费</font>','<font class="text-danger">已退款</font>'];
                $.each(result.data.data.data,function(key,item){
                    var linkList = {"name":item.name,"price":item.price,"pay_status":pay_status[item.pay_status],"start_time":convertTimestamp(item.start_time),"end_time":convertTimestamp(item.end_time)};
                    if(users_id != 0){
                        var method = `<a href="/admin/links_lists/member_orders_update/${item.id}" class="text-primary" target="_blank">更新</a>`;
                        linkList.method = method;
                    }
                    linkLists.push(linkList);
                });
                var dataResult = {rows:linkLists,total:result.data.data.total};
                params.success(dataResult);
            } else {
                messageToastr("error",result.msg);
            }
        },
        error: function(err){
            messageToastr("error",'请求失败，请检查网络');
        }
    });
}

function withdrawalLists(params){
    if($("#cangetwithdrawal").val() == 0) return false;
    params.data.status = $("#is_status").val();
    params.data.nav = $("#navbar_num").val();
    params.data.page = Number(params.data.offset/params.data.limit) + 1;
    let users_id = $('#users_id').val();
    let url = users_id==0 ? `/admin/users/api_users_detial` : `/admin/users/api_users_detial/${users_id}`;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: params.data,
        success:function (result) {
            if (result.status == "success") {
                var linkLists = [];
                $.each(result.data.data.data,function(key,item){
                    var wi_status = item.status == 1 ? '未成功' : '<font class="text-success">成功</font>';
                    var linkList = {"name":item.name,"alipay":item.alipay,"money":item.money,"status":wi_status,"created_at":item.created_at};
                    linkLists.push(linkList);
                });
                var dataResult = {rows:linkLists,total:result.data.data.total};
                params.success(dataResult);
            } else {
                messageToastr("error",result.msg);
            }
        },
        error: function(err){
            messageToastr("error",'请求失败，请检查网络');
        }
    });
}

function notesLists(params){
    let users_id = $('#users_id').val();
    if($("#cangetnotes").val() == 0 || users_id==0) return false;
    params.data.nav = $("#navbar_num").val();
    params.data.page = Number(params.data.offset/params.data.limit) + 1;
    let url = users_id==0 ? `/admin/users/api_users_detial` : `/admin/users/api_users_detial/${users_id}`;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: params.data,
        success:function (result) {
            if (result.status == "success") {
                var linkLists = [];
                $.each(result.data.data.data,function(key,item){
                    var describe = `<font style="word-break: break-all;">${item.describe}</font>`
                    var linkList = {"title":item.title,"describe":describe,"created_at":item.created_at};
                    linkLists.push(linkList);
                });
                var dataResult = {rows:linkLists,total:result.data.data.total};
                params.success(dataResult);
            } else {
                messageToastr("error",result.msg);
            }
        },
        error: function(err){
            messageToastr("error",'请求失败，请检查网络');
        }
    });
}

function inviteLists(params){
    let users_id = $('#users_id').val();
    if($("#cangetinvite").val() == 0 ) return false;
    params.data.nav = $("#navbar_num").val();
    params.data.nike = $("#invite_nike").val();
    params.data.page = Number(params.data.offset/params.data.limit) + 1;
    let url = users_id==0 ? `/admin/users/api_users_detial` : `/admin/users/api_users_detial/${users_id}`;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: params.data,
        success:function (result) {
            if (result.status == "success") {
                var linkLists = [];
                var product_lists = ['免费版','基础版','高级版','旗舰版'];
                $.each(result.data.data.data,function(key,item){
                    var avatar = item.avatar ||  '/images/avatar.png';
                    try{
                        var niketext = item.nike.slice(0,5)
                    }catch(e){
                        var niketext = '-'
                    }
                    var nike = `<img src="${avatar}" style="width: 30px;height: 30px;border-radius: 50%;margin-right: 5px;">${niketext}`;
                    var describe = `<font style="word-break: break-all;">${item.describe}</font>`
                    var linkList = {"nike":item.nike,"username":item.username,"product_id":product_lists[item.product_id],"member_time":item.member_time,"created_at":item.created_at,"method":'-'};
                    linkLists.push(linkList);
                });
                var dataResult = {rows:linkLists,total:result.data.data.total};
                params.success(dataResult);
            } else {
                messageToastr("error",result.msg);
            }
        },
        error: function(err){
            messageToastr("error",'请求失败，请检查网络');
        }
    });
}

function loadingTemplate(message) {
    return '<div style="font-size:14px;display: flex;align-items: center;flex-direction: row;"><i class="bx bx-loader-alt bx-spin me-2"></i>数据加载中,请稍等...</div>'
}

function convertTimestamp(timestamp) {
    timestamp = Number(timestamp) > 10000000000000 ? timestamp : timestamp*1000;
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    const hours = ('0' + date.getHours()).slice(-2);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);
    const convertedDate = `${year}-${month}-${day}`;
    const convertedTime = `${hours}:${minutes}:${seconds}`;
    return `${convertedDate} ${convertedTime}`;
}
function remarkShow(){
    $('#remarkModal').modal('toggle');
}

function remarkssubmit() {
    var remarks_title = $("#remarks_title").val();
    var remarks_describe = $("#remarks_describe").val();
    if (remarks_title.length <= 5) {
        mviewToastr("error","请输入5字以上标题！");
        return false;
    }
    if (remarks_describe.length <= 10) {
        mviewToastr("error","请输入10字以上备注！");
        return false;
    }
    $.ajax({
        "url": "/admin/users/remarks_add",
        "type": "GET",
        "data": {
            "users_id": $('#users_id').val(),
            "title": remarks_title,
            "describe": remarks_describe,
        },
        success: function(res){
            if (res.status == "success") {
                mviewToastr("success",res.msg);
                remarkShow();
                notesReload();
                $("#remarks_title").val('');
                $("#remarks_describe").val('');
            } else {
                mviewToastr("error",res.msg);
            }
        },
        fail: function(err){
            mviewToastr("error",'网络异常,请稍后重试');
        }
    });
}

function statusShow(){
    $('#statusModal').modal('toggle');
}

function statusSubmit(){
    $.ajax({
        "url": "/admin/users/update_status",
        "type": "GET",
        "data": {
            "users_id": $('#users_id').val(),
            "status": $("#genjin-status").val(),
        },
        success: function(res){
            if (res.status == "success") {
                mviewToastr("success",res.msg);
                statusShow();
                var tip = [
                    {"u_name":"","u_class":""},
                    {"u_name":"未跟进","u_class":"text-warning"},
                    {"u_name":"无法接通","u_class":"text-info"},
                    {"u_name":"有意向","u_class":"text-success"},
                    {"u_name":"无意向","u_class":"text-danger"},
                    {"u_name":"待跟进","u_class":"text-warning"}];
                $("#status-tip").text(tip[$('#genjin-status').val()].u_name);
                $("#status-tip").removeClass();
                $("#status-tip").addClass(tip[$('#genjin-status').val()].u_class);


            } else {
                mviewToastr("error",res.msg);
            }
        },
        fail: function(err){
            mviewToastr("error",'网络异常,请稍后重试');
        }
    });
}

function confirmMviewNotification() {
    var mviewNotificationData = $("#mviewNotificationData").val();
    var notificationData = JSON.parse(mviewNotificationData);
    if(notificationData.type == "mini_delete"){
        minideletesubmit(notificationData.appid)
    }
    colseMviewNotification();
    // console.log(notificationData);
}

function minideletesubmit(appid) {
    $.ajax({
        "url": "/admin/miniapp/minapp_delete",
        "type": "GET",
        "data": {
            "users_id": $('#users_id').val(),
            "appid": appid,
        },
        success: function(res){
            if (res.status == "success") {
                mviewToastr("success",res.msg);
                miniReload();
            } else {
                mviewToastr("error",res.msg);
            }
        },
        fail: function(err){
            mviewToastr("error",'网络异常,请稍后重试');
        }
    });
}